#coding=utf-8
'''
Created on 2017-6-15

@author: sandy
'''

#from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet.protocol import ClientFactory
from twisted.internet import reactor
import logging
import serverconfig
from twisted.internet import protocol
import timecheck

class ProxyServerFactory(ClientFactory):
    def __init__(self,srv):
        #ReconnectingClientFactory.maxDelay = 5
        self.srv = srv
    
    def buildProtocol(self, addr):
        logging.warn(u"ProxyServerFactory buildProtocol!!!")
        #self.resetDelay()
        return self.srv

    def startedConnecting(self, connector):
        logging.warn(u"ProxyServerFactory startedConnecting!!!")
    
    def clientConnectionLost(self, connector, reason):
        logging.warn(u"ProxyServerFactory clientConnectionLost!!!")
        ClientFactory.clientConnectionLost(self, connector, reason)
        
    def clientConnectionFailed(self, connector, reason):
        logging.warn(u"ProxyServerFactory clientConnectionFailed!!!")
        ClientFactory.clientConnectionFailed(self, connector, reason)

class ProxyServerSrv(protocol.Protocol):
                      
    def __init__(self):
        self.client = None
        pass
    
    def start(self): 
        reactor.connectTCP(serverconfig.instance.server_ip,serverconfig.instance.server_port,ProxyServerFactory(self))
        
    def stop(self):
        pass
    
    def connectionMade(self):
        timecheck.instance.updateTime(self)
        logging.warn(u"MysqlSrv connectionMade()")
        pass

    def connectionLost(self, reason=protocol.connectionDone):
        logging.debug(u"MysqlSrv connectionLost()")
        if self.client:
            self.client.abort()
        else:
            logging.warn(u"connectionLost:this is no client")
        
    def setClient(self,client):
        self.client = client

    def dataReceived(self, data):
        timecheck.instance.updateTime(self)
        if self.client:
            self.client.sendPacket(data)
        else:
            logging.warn(u"dataReceived:this is no client")

    def sendPacket(self, data):
        self.transport.write(data)

    def about(self):
        self.transport.abortConnection()

   
if __name__ == '__main__':
    pass